<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "6d134c3b"
    });
  daovoice('update');
  </script>




















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.1" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.1">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.1" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.4.1',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="按键精灵想必很多人都玩过，使用录制功能将鼠标和键盘的操作录制下来，录制好后就可以通过回放自动执行之前录制的操作，可以设置重复执行的次数，这样就可以将一些重复的劳动交给脚本自动化去完成。使用Python编写一个和脚本精灵一样的程序非常简单，并且代码量足够少，好处是可以不再依赖按键精灵，像我这种有轻微洁癖的程序猿就喜欢自己动手实现,依赖Python的为所欲为的特性，可以任意编码让自己的按键精灵更加强大">
<meta name="keywords" content="Python">
<meta property="og:type" content="article">
<meta property="og:title" content="使用Python实现一个按键精灵">
<meta property="og:url" content="https://www.lanshiqin.com/2fb233e2/index.html">
<meta property="og:site_name" content="蓝士钦">
<meta property="og:description" content="按键精灵想必很多人都玩过，使用录制功能将鼠标和键盘的操作录制下来，录制好后就可以通过回放自动执行之前录制的操作，可以设置重复执行的次数，这样就可以将一些重复的劳动交给脚本自动化去完成。使用Python编写一个和脚本精灵一样的程序非常简单，并且代码量足够少，好处是可以不再依赖按键精灵，像我这种有轻微洁癖的程序猿就喜欢自己动手实现,依赖Python的为所欲为的特性，可以任意编码让自己的按键精灵更加强大">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://www.lanshiqin.com/2fb233e2/mouse_keyboard_py.png">
<meta property="og:updated_time" content="2019-03-03T13:53:01.058Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用Python实现一个按键精灵">
<meta name="twitter:description" content="按键精灵想必很多人都玩过，使用录制功能将鼠标和键盘的操作录制下来，录制好后就可以通过回放自动执行之前录制的操作，可以设置重复执行的次数，这样就可以将一些重复的劳动交给脚本自动化去完成。使用Python编写一个和脚本精灵一样的程序非常简单，并且代码量足够少，好处是可以不再依赖按键精灵，像我这种有轻微洁癖的程序猿就喜欢自己动手实现,依赖Python的为所欲为的特性，可以任意编码让自己的按键精灵更加强大">
<meta name="twitter:image" content="https://www.lanshiqin.com/2fb233e2/mouse_keyboard_py.png">



  <link rel="alternate" href="/atom.xml" title="蓝士钦" type="application/atom+xml" />




  <link rel="canonical" href="https://www.lanshiqin.com/2fb233e2/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>使用Python实现一个按键精灵 | 蓝士钦</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

  <script src="/js/src/photoswipe.js?v="></script>
  <script src="/js/src/photoswipe-ui-default.js?v="></script>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蓝士钦</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">编程是一种信仰</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-相册">
    <a href="/photos/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />相册</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.lanshiqin.com/2fb233e2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="蓝士钦">
      <meta itemprop="description" content="编程是一种信仰">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蓝士钦">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">使用Python实现一个按键精灵
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-01-17 19:11:59" itemprop="dateCreated datePublished" datetime="2019-01-17T19:11:59+08:00">2019-01-17</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-03-03 21:53:01" itemprop="dateModified" datetime="2019-03-03T21:53:01+08:00">2019-03-03</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>按键精灵想必很多人都玩过，使用录制功能将鼠标和键盘的操作录制下来，录制好后就可以通过回放自动执行之前录制的操作，可以设置重复执行的次数，这样就可以将一些重复的劳动交给脚本自动化去完成。使用Python编写一个和脚本精灵一样的程序非常简单，并且代码量足够少，好处是可以不再依赖按键精灵，像我这种有轻微洁癖的程序猿就喜欢自己动手实现,依赖Python的为所欲为的特性，可以任意编码让自己的<code>按键精灵</code>更加强大。<br><a id="more"></a><br><code>按键精灵</code>的实现可以拆解分为录制和回放两个步骤，对应到Python程序的实现也可以分为两步：<br>1.监听鼠标键盘的事件和坐标，写入到文件中记录起来。<br>2.读取监听时写入的文件，执行文件中的坐标和事件操作。</p>
<p>要实现这两个功能，得先从基础开始。我把任务拆解成两大部分，鼠标和键盘属于不同的两个输入设备，所以分开实现“鼠标精灵”和“键盘精灵”两个程序，最后融合这两个模块实现一个相对完整的按键精灵。</p>
<p>Python操作键盘鼠标的库推荐<code>pynput</code>这个库、地址：<br><a href="https://pypi.org/project/pynput/" target="_blank" rel="noopener">https://pypi.org/project/pynput/</a></p>
<h1 id="鼠标事件监听"><a href="#鼠标事件监听" class="headerlink" title="鼠标事件监听"></a>鼠标事件监听</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> pynput <span class="keyword">import</span> mouse</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标移动事件</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">on_move</span><span class="params">(x, y)</span>:</span></span><br><span class="line">    print(<span class="string">'[Move]'</span>, (x, y))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标点击事件</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">on_click</span><span class="params">(x, y, button, pressed)</span>:</span></span><br><span class="line">    print(<span class="string">'[Click]'</span>, (x, y, button.name, pressed))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标滚动事件</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">on_scroll</span><span class="params">(x, y, x_axis, y_axis)</span>:</span></span><br><span class="line">    print(<span class="string">'[Scroll]'</span>, (x, y, x_axis, y_axis))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 监听事件绑定</span></span><br><span class="line"><span class="keyword">with</span> mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) <span class="keyword">as</span> listener:</span><br><span class="line">    listener.join()</span><br></pre></td></tr></table></figure>
<p><code>onMove(x,y)</code>函数接收鼠标当前的x轴和y轴坐标，启动程序并移动鼠标时，就会调用该方法。<br><code>on_click(x, y, button, pressed)</code>函数接收鼠标的点击事件，x和y为当前点击事件的鼠标坐标，<code>button</code>参数对象的<code>name</code>属性值为<code>left</code>或者<code>right</code>,通过该属性值可以判断是鼠标的左键还是右键产生的点击事件。<br><code>pressed</code>参数值为<code>True</code>时表示当前鼠标左或右键按压，<code>False</code>时表示鼠标左或右键抬起事件<br><code>on_scroll(x, y, x_axis, y_axis)</code>接收四个参数，前两个参数依旧是当前事件的鼠标坐标轴，<code>x_axis</code>的值&gt;0表示向上，&lt;0表示向下，同样的<code>y_axis</code>的负值和正值代表左滑和右滑状态。<br>当</p>
<h1 id="鼠标事件执行"><a href="#鼠标事件执行" class="headerlink" title="鼠标事件执行"></a>鼠标事件执行</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> pynput.mouse <span class="keyword">import</span> Button, Controller</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取鼠标对象</span></span><br><span class="line">mouse = Controller()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出鼠标当前的坐标</span></span><br><span class="line">print(mouse.position)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 将新的坐标赋值给鼠标对象</span></span><br><span class="line">mouse.position = (<span class="number">100</span>, <span class="number">500</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> index <span class="keyword">in</span> range(<span class="number">0</span>, <span class="number">30</span>):</span><br><span class="line">    <span class="comment"># 鼠标移动到指定坐标轴</span></span><br><span class="line">    mouse.move(index, -index)</span><br><span class="line">    print(mouse.position)</span><br><span class="line">    time.sleep(<span class="number">0.01</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> index <span class="keyword">in</span> range(<span class="number">0</span>, <span class="number">30</span>):</span><br><span class="line">    <span class="comment"># 鼠标移动到指定坐标轴</span></span><br><span class="line">    mouse.move(-index, index)</span><br><span class="line">    print(mouse.position)</span><br><span class="line">    time.sleep(<span class="number">0.01</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标右键按下</span></span><br><span class="line">mouse.press(Button.right)</span><br><span class="line"></span><br><span class="line">time.sleep(<span class="number">0.01</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标右键抬起</span></span><br><span class="line">mouse.release(Button.right)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标左键点击</span></span><br><span class="line">mouse.click(Button.left, <span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标滚轮滚动距离500</span></span><br><span class="line">mouse.scroll(<span class="number">0</span>, <span class="number">500</span>)</span><br></pre></td></tr></table></figure>
<p>和鼠标事件监听一样，对应的我们可以操作鼠标的各种事件：移动、左/右按压、左/右抬起、左/右点击、上下左右滚动<br>上面代码中的<code>mouse.move(x,y)</code>函数，表示从当前鼠标位置进行位移的距离，x和y的值是以当前位置为0点开始算的。<br>而且不能简单的用坐标轴去相减得到位移距离，所以后续的程序我会使用<code>mouse.position = (x, y)</code>这个函数来操作鼠标的移动，<br>这个函数可以将鼠标设置到指定位置，只要我们记录之前的鼠标移动轨迹，就可以通过读取之前的记录文件按顺序重新对鼠标进行赋值操作。达到回放的效果。</p>
<h1 id="带录制回放功能的鼠标精灵"><a href="#带录制回放功能的鼠标精灵" class="headerlink" title="带录制回放功能的鼠标精灵"></a>带录制回放功能的鼠标精灵</h1><p>结合鼠标事件的监听和执行，并且将事件记录到文件中，再加上Python自带的GUI，就可以写出一个简单的鼠标精灵了。<br>实现思路：</p>
<ol>
<li>定义一个json格式的对象来统一不同鼠标事件的内容格式<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="attr">"name"</span>:<span class="string">"mouse"</span>,</span><br><span class="line">    <span class="attr">"event"</span>:<span class="string">"click"</span>,</span><br><span class="line">    <span class="attr">"target"</span>:<span class="string">"left"</span>,</span><br><span class="line">    <span class="attr">"action"</span>:<span class="literal">true</span>,</span><br><span class="line">    <span class="attr">"location"</span>:&#123;</span><br><span class="line">        <span class="attr">"x"</span>:<span class="string">"0"</span>,</span><br><span class="line">        <span class="attr">"y"</span>:<span class="string">"0"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>鼠标事件的<code>name</code>值为<code>mouse</code>,考虑到后续还有可能会有其他设备的事件，比如键盘事件。<br>鼠标的事件为点击事件，将<code>event</code>赋值为<code>click</code>。<br><code>target</code>表示目标，点击了鼠标左键,所以目标值为<code>left</code><br><code>action</code>表示动作，鼠标点击分为按压和抬起，<code>true</code>表示抬起。<br><code>location</code>的值包含一个json对象，里面为当前事件鼠标的x和y坐标。<br>鼠标的移动和滑动事件以此类推，用同样的模板格式进行记录。</p>
<ol start="2">
<li>将记录的数据写入到文件中</li>
<li>执行回放时通过逐行读取文件，解析文件中的json数据通过<code>name</code>、<code>event</code>、<code>location</code>等值进行事件执行。</li>
</ol>
<p>之所以选择json时因为解析起来比较方便。当然你也可以使用数据库，比如SQLite等，或者自己定义一套自己的格式。<br>json的存储方式有太多的冗余字符了，空间占用目前不是考虑的首要因素，这里先用最快的方式实现它。</p>
<p>GUI用了Python自带的<code>tkinter</code>库，为了防止UI阻塞，所以使用了多线程，同样是Python自带库<code>threading</code>。<br>整个实现其实只用了一个三方库 <code>pynput</code></p>
<p>鼠标事件的监听录制和执行回放的完整代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> json</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> tkinter</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> pynput <span class="keyword">import</span> mouse</span><br><span class="line"><span class="keyword">from</span> pynput.mouse <span class="keyword">import</span> Button, Controller</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标动作模板</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">mouse_action_template</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        <span class="string">"name"</span>: <span class="string">"mouse"</span>,</span><br><span class="line">        <span class="string">"event"</span>: <span class="string">"default"</span>,</span><br><span class="line">        <span class="string">"target"</span>: <span class="string">"default"</span>,</span><br><span class="line">        <span class="string">"action"</span>: <span class="string">"default"</span>,</span><br><span class="line">        <span class="string">"location"</span>: &#123;</span><br><span class="line">            <span class="string">"x"</span>: <span class="string">"0"</span>,</span><br><span class="line">            <span class="string">"y"</span>: <span class="string">"0"</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标动作监听</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MouseActionListener</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, file_name)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.file_name = file_name</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">with</span> open(self.file_name, <span class="string">'w'</span>, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">            <span class="comment"># 鼠标移动事件</span></span><br><span class="line">            <span class="function"><span class="keyword">def</span> <span class="title">on_move</span><span class="params">(x, y)</span>:</span></span><br><span class="line">                template = mouse_action_template()</span><br><span class="line">                template[<span class="string">'event'</span>] = <span class="string">'move'</span></span><br><span class="line">                template[<span class="string">'location'</span>][<span class="string">'x'</span>] = x</span><br><span class="line">                template[<span class="string">'location'</span>][<span class="string">'y'</span>] = y</span><br><span class="line">                file.writelines(json.dumps(template) + <span class="string">"\n"</span>)</span><br><span class="line">                file.flush()</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 鼠标点击事件</span></span><br><span class="line">            <span class="function"><span class="keyword">def</span> <span class="title">on_click</span><span class="params">(x, y, button, pressed)</span>:</span></span><br><span class="line">                template = mouse_action_template()</span><br><span class="line">                template[<span class="string">'event'</span>] = <span class="string">'click'</span></span><br><span class="line">                template[<span class="string">'target'</span>] = button.name</span><br><span class="line">                template[<span class="string">'action'</span>] = pressed</span><br><span class="line">                template[<span class="string">'location'</span>][<span class="string">'x'</span>] = x</span><br><span class="line">                template[<span class="string">'location'</span>][<span class="string">'y'</span>] = y</span><br><span class="line">                file.writelines(json.dumps(template) + <span class="string">"\n"</span>)</span><br><span class="line">                file.flush()</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 鼠标滚动事件</span></span><br><span class="line">            <span class="function"><span class="keyword">def</span> <span class="title">on_scroll</span><span class="params">(x, y, x_axis, y_axis)</span>:</span></span><br><span class="line">                template = mouse_action_template()</span><br><span class="line">                template[<span class="string">'event'</span>] = <span class="string">'scroll'</span></span><br><span class="line">                template[<span class="string">'location'</span>][<span class="string">'x'</span>] = x_axis</span><br><span class="line">                template[<span class="string">'location'</span>][<span class="string">'y'</span>] = y_axis</span><br><span class="line">                file.writelines(json.dumps(template) + <span class="string">"\n"</span>)</span><br><span class="line">                file.flush()</span><br><span class="line"></span><br><span class="line">            <span class="keyword">with</span> mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) <span class="keyword">as</span> listener:</span><br><span class="line">                listener.join()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标动作执行</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MouseActionExecute</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, file_name)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.file_name = file_name</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">with</span> open(self.file_name, <span class="string">'r'</span>, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">            mouse_exec = Controller()</span><br><span class="line">            line = file.readline()</span><br><span class="line">            time.sleep(<span class="number">0.01</span>)</span><br><span class="line">            <span class="keyword">while</span> line:</span><br><span class="line">                obj = json.loads(line)</span><br><span class="line">                <span class="keyword">if</span> obj[<span class="string">'name'</span>] == <span class="string">'mouse'</span>:</span><br><span class="line">                    <span class="keyword">if</span> obj[<span class="string">'event'</span>] == <span class="string">'move'</span>:</span><br><span class="line">                        mouse_exec.position = (obj[<span class="string">'location'</span>][<span class="string">'x'</span>], obj[<span class="string">'location'</span>][<span class="string">'y'</span>])</span><br><span class="line">                        time.sleep(<span class="number">0.01</span>)</span><br><span class="line">                    <span class="keyword">elif</span> obj[<span class="string">'event'</span>] == <span class="string">'click'</span>:</span><br><span class="line">                        <span class="keyword">if</span> obj[<span class="string">'action'</span>]:</span><br><span class="line">                            <span class="keyword">if</span> obj[<span class="string">'target'</span>] == <span class="string">'left'</span>:</span><br><span class="line">                                mouse_exec.press(Button.left)</span><br><span class="line">                            <span class="keyword">else</span>:</span><br><span class="line">                                mouse_exec.press(Button.right)</span><br><span class="line">                        <span class="keyword">else</span>:</span><br><span class="line">                            <span class="keyword">if</span> obj[<span class="string">'target'</span>] == <span class="string">'left'</span>:</span><br><span class="line">                                mouse_exec.release(Button.left)</span><br><span class="line">                            <span class="keyword">else</span>:</span><br><span class="line">                                mouse_exec.release(Button.right)</span><br><span class="line">                        time.sleep(<span class="number">0.01</span>)</span><br><span class="line">                    <span class="keyword">elif</span> obj[<span class="string">'event'</span>] == <span class="string">'scroll'</span>:</span><br><span class="line">                        mouse_exec.scroll(obj[<span class="string">'location'</span>][<span class="string">'x'</span>], obj[<span class="string">'location'</span>][<span class="string">'y'</span>])</span><br><span class="line">                        time.sleep(<span class="number">0.01</span>)</span><br><span class="line">                line = file.readline()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">button_onClick</span><span class="params">(action)</span>:</span></span><br><span class="line"></span><br><span class="line">    m1 = MouseActionListener(file_name=<span class="string">'mouse.action'</span>)</span><br><span class="line">    m2 = MouseActionExecute(file_name=<span class="string">'mouse.action'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> action == <span class="string">'listener'</span>:</span><br><span class="line">        <span class="keyword">if</span> startListenerBtn[<span class="string">'text'</span>] == <span class="string">'录制'</span>:</span><br><span class="line">            m1.start()</span><br><span class="line">            startListenerBtn[<span class="string">'text'</span>] = <span class="string">'录制中...关闭程序停止录制'</span></span><br><span class="line">            startListenerBtn[<span class="string">'state'</span>] = <span class="string">'disabled'</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">elif</span> action == <span class="string">'execute'</span>:</span><br><span class="line">        <span class="keyword">if</span> startExecuteBtn[<span class="string">'text'</span>] == <span class="string">'回放'</span>:</span><br><span class="line">            m2.start()</span><br><span class="line">            startExecuteBtn[<span class="string">'text'</span>] = <span class="string">'回放中...关闭程序停止回放'</span></span><br><span class="line">            startExecuteBtn[<span class="string">'state'</span>] = <span class="string">'disabled'</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line"></span><br><span class="line">    root = tkinter.Tk()</span><br><span class="line">    root.title(<span class="string">'鼠标精灵-蓝士钦'</span>)</span><br><span class="line">    root.geometry(<span class="string">'200x200+400+100'</span>)</span><br><span class="line"></span><br><span class="line">    startListenerBtn = tkinter.Button(root, text=<span class="string">"录制"</span>, command=<span class="keyword">lambda</span>: button_onClick(<span class="string">'listener'</span>))</span><br><span class="line">    startListenerBtn.place(x=<span class="number">10</span>, y=<span class="number">10</span>, width=<span class="number">180</span>, height=<span class="number">80</span>)</span><br><span class="line"></span><br><span class="line">    startExecuteBtn = tkinter.Button(root, text=<span class="string">"回放"</span>, command=<span class="keyword">lambda</span>: button_onClick(<span class="string">'execute'</span>))</span><br><span class="line">    startExecuteBtn.place(x=<span class="number">10</span>, y=<span class="number">110</span>, width=<span class="number">180</span>, height=<span class="number">80</span>)</span><br><span class="line">    root.mainloop()</span><br></pre></td></tr></table></figure>
<p>按键精灵的鼠标部分到这里就基本完成了。<br>运行程序，点击<code>录制</code>，然后就可以用你的鼠标在屏幕上一顿操作。然后关闭本程序。<br>接着重新打开程序，点击<code>回放</code>，就会发现鼠标可以按照之前录制的动作进行自动工作了。<br>记住千万不要在<code>录制</code>时，还没关闭程序的时候就点击<code>回放</code>，这样会陷入无限循环里面，会导致不停的录制不停的回放。<br>还有键盘的程序后续补上，程序待完善中，未完待续。</p>
<h1 id="键盘事件监听"><a href="#键盘事件监听" class="headerlink" title="键盘事件监听"></a>键盘事件监听</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> pynput <span class="keyword">import</span> keyboard</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 按键按下监听</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">on_press</span><span class="params">(key)</span>:</span></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        print(<span class="string">'press key &#123;0&#125;, vk: &#123;1&#125;'</span>.format(key.char, key.vk))</span><br><span class="line">    <span class="keyword">except</span> AttributeError:</span><br><span class="line">        print(<span class="string">'special press key &#123;0&#125;, vk: &#123;1&#125;'</span>.format(key, key.value.vk))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 按键释放监听</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">on_release</span><span class="params">(key)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> key == keyboard.Key.esc:</span><br><span class="line">        <span class="comment"># 停止监听</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">False</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        print(<span class="string">'release key &#123;0&#125;, vk: &#123;1&#125;'</span>.format(key.char, key.vk))</span><br><span class="line">    <span class="keyword">except</span> AttributeError:</span><br><span class="line">        print(<span class="string">'special release key &#123;0&#125;, vk: &#123;1&#125;'</span>.format(key, key.value.vk))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 键盘监听</span></span><br><span class="line"><span class="keyword">with</span> keyboard.Listener(on_press=on_press, on_release=on_release) <span class="keyword">as</span> listener:</span><br><span class="line">    listener.join()</span><br></pre></td></tr></table></figure>
<p>键盘监听相对于鼠标监听来说，回调的函数只有两个<code>on_press</code>按键按下 和<code>on_release</code>按键释放。<br>由于<code>pynput</code>这个库对键盘的不同按键事件封装进行了区分，比如普通的数字和字母键按下会进入<code>on_press</code>方法，通过传入的<code>key.char</code>属性值可以得到按键对应在键盘上的字符，但如果是Shift等其他特殊键，就没有<code>char</code>属性，会产生异常。<br>只要捕获异常后直接通过<code>key</code>就可以取到特殊键对应的字符。我觉得这是<code>pynput</code>做得有点不够优雅的地方。<br>普通的键有<code>key.vk</code>属性值，代表键盘上字符对应的编码值，特殊键的编码值要通过<code>key.value.vk</code>来取。</p>
<h1 id="键盘事件执行"><a href="#键盘事件执行" class="headerlink" title="键盘事件执行"></a>键盘事件执行</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> pynput.keyboard <span class="keyword">import</span> Key, Controller, KeyCode</span><br><span class="line"></span><br><span class="line"><span class="comment"># 键盘控制对象</span></span><br><span class="line">keyboard = Controller()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 按下 a 键</span></span><br><span class="line">keyboard.press(<span class="string">'a'</span>)</span><br><span class="line"><span class="comment"># 释放 a 键</span></span><br><span class="line">keyboard.release(<span class="string">'a'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 按下 Shift 键</span></span><br><span class="line">keyboard.press(Key.shift)</span><br><span class="line">keyboard.press(<span class="string">'b'</span>)</span><br><span class="line">keyboard.release(<span class="string">'b'</span>)</span><br><span class="line">keyboard.press(<span class="string">'c'</span>)</span><br><span class="line">keyboard.release(<span class="string">'c'</span>)</span><br><span class="line"><span class="comment"># 释放 Shift 键</span></span><br><span class="line">keyboard.release(Key.esc)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 按下 Shift 键，然后依次按下其他按键，完成后Shift键自动释放</span></span><br><span class="line"><span class="keyword">with</span> keyboard.pressed(Key.shift):</span><br><span class="line">    keyboard.press(<span class="string">'d'</span>)</span><br><span class="line">    keyboard.release(<span class="string">'d'</span>)</span><br><span class="line">    keyboard.press(<span class="string">'e'</span>)</span><br><span class="line">    keyboard.release(<span class="string">'e'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 依次按下 python （包括前面的空格）</span></span><br><span class="line">keyboard.type(<span class="string">' python'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 按下 vk值为56的键 shift 键</span></span><br><span class="line">keyboard.touch(KeyCode.from_vk(<span class="number">56</span>), <span class="keyword">True</span>)</span><br><span class="line">keyboard.touch(<span class="string">'a'</span>, <span class="keyword">True</span>)</span><br><span class="line">keyboard.touch(<span class="string">'a'</span>, <span class="keyword">False</span>)</span><br><span class="line"><span class="comment"># 释放 shift 键</span></span><br><span class="line">keyboard.touch(Key.shift, <span class="keyword">False</span>)</span><br></pre></td></tr></table></figure>
<p>和监听方法对应，执行键盘的按键方法有<code>press(key)</code>按压 <code>release(key)</code>释放。<br>除此之外还有<code>touch(key,is_press)</code>函数,key表示要操作的键，is_press 为True时表示按压，为False时表示释放。<br>无论是哪种按压事件，Key都可以通过其他方式构造，比如知道Shift的vk值为56，那么就可以通过<code>KeyCode.from_vk(56)</code>来构造一个Shift的Key。<br>通过VK编码构造Key的方式很有用，因为当你要按出一个<code>@</code>符号时，需要同时按住<code>Shift</code>和<code>2</code>。通过<code>on_press(key)</code>监听得到的值是一个<code>@</code>符号，如果录制程序录制了一个<code>@</code>符号将无法通过<code>keyboard.press(&#39;@&#39;)</code>这种方式直接执行。<br>所以接下来的键盘录制回放程序我将通过定义一个键盘动作模板，然后通过VK值准确的记录每个键以及每个组合键的编码。然后通过<code>keyboard.press(KeyCode.from_vk(vk))</code>进行回放。</p>
<h1 id="带录制回放功能的键盘精灵"><a href="#带录制回放功能的键盘精灵" class="headerlink" title="带录制回放功能的键盘精灵"></a>带录制回放功能的键盘精灵</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> json</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> tkinter</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> pynput <span class="keyword">import</span> keyboard</span><br><span class="line"><span class="keyword">from</span> pynput.keyboard <span class="keyword">import</span> Controller, KeyCode</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 键盘动作模板</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">keyboard_action_template</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        <span class="string">"name"</span>: <span class="string">"keyboard"</span>,</span><br><span class="line">        <span class="string">"event"</span>: <span class="string">"default"</span>,</span><br><span class="line">        <span class="string">"vk"</span>: <span class="string">"default"</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 键盘动作监听</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">KeyboardActionListener</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, file_name)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.file_name = file_name</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">with</span> open(self.file_name, <span class="string">'w'</span>, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">            <span class="comment"># 键盘按下监听</span></span><br><span class="line">            <span class="function"><span class="keyword">def</span> <span class="title">on_press</span><span class="params">(key)</span>:</span></span><br><span class="line">                template = keyboard_action_template()</span><br><span class="line">                template[<span class="string">'event'</span>] = <span class="string">'press'</span></span><br><span class="line">                <span class="keyword">try</span>:</span><br><span class="line">                    template[<span class="string">'vk'</span>] = key.vk</span><br><span class="line">                <span class="keyword">except</span> AttributeError:</span><br><span class="line">                    template[<span class="string">'vk'</span>] = key.value.vk</span><br><span class="line">                <span class="keyword">finally</span>:</span><br><span class="line">                    file.writelines(json.dumps(template) + <span class="string">"\n"</span>)</span><br><span class="line">                    file.flush()</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 键盘抬起监听</span></span><br><span class="line">            <span class="function"><span class="keyword">def</span> <span class="title">on_release</span><span class="params">(key)</span>:</span></span><br><span class="line">                <span class="keyword">if</span> key == keyboard.Key.esc:</span><br><span class="line">                    <span class="comment"># 停止监听</span></span><br><span class="line">                    startListenerBtn[<span class="string">'text'</span>] = <span class="string">'录制'</span></span><br><span class="line">                    startListenerBtn[<span class="string">'state'</span>] = <span class="string">'normal'</span></span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">False</span></span><br><span class="line">                template = keyboard_action_template()</span><br><span class="line">                template[<span class="string">'event'</span>] = <span class="string">'release'</span></span><br><span class="line">                <span class="keyword">try</span>:</span><br><span class="line">                    template[<span class="string">'vk'</span>] = key.vk</span><br><span class="line">                <span class="keyword">except</span> AttributeError:</span><br><span class="line">                    template[<span class="string">'vk'</span>] = key.value.vk</span><br><span class="line">                <span class="keyword">finally</span>:</span><br><span class="line">                    file.writelines(json.dumps(template) + <span class="string">"\n"</span>)</span><br><span class="line">                    file.flush()</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 键盘监听</span></span><br><span class="line">            <span class="keyword">with</span> keyboard.Listener(on_press=on_press, on_release=on_release) <span class="keyword">as</span> listener:</span><br><span class="line">                listener.join()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 键盘动作执行</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">KeyboardActionExecute</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, file_name)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.file_name = file_name</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">with</span> open(self.file_name, <span class="string">'r'</span>, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">            keyboard_exec = Controller()</span><br><span class="line">            line = file.readline()</span><br><span class="line">            time.sleep(<span class="number">3</span>)</span><br><span class="line">            <span class="keyword">while</span> line:</span><br><span class="line">                obj = json.loads(line)</span><br><span class="line">                <span class="keyword">if</span> obj[<span class="string">'name'</span>] == <span class="string">'keyboard'</span>:</span><br><span class="line">                    <span class="keyword">if</span> obj[<span class="string">'event'</span>] == <span class="string">'press'</span>:</span><br><span class="line">                        keyboard_exec.press(KeyCode.from_vk(obj[<span class="string">'vk'</span>]))</span><br><span class="line">                        time.sleep(<span class="number">0.01</span>)</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">elif</span> obj[<span class="string">'event'</span>] == <span class="string">'release'</span>:</span><br><span class="line">                        keyboard_exec.release(KeyCode.from_vk(obj[<span class="string">'vk'</span>]))</span><br><span class="line">                        time.sleep(<span class="number">0.01</span>)</span><br><span class="line">                line = file.readline()</span><br><span class="line">            startExecuteBtn[<span class="string">'text'</span>] = <span class="string">'回放'</span></span><br><span class="line">            startExecuteBtn[<span class="string">'state'</span>] = <span class="string">'normal'</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">button_onClick</span><span class="params">(action)</span>:</span></span><br><span class="line">    m1 = KeyboardActionListener(file_name=<span class="string">'keyboard.action'</span>)</span><br><span class="line">    m2 = KeyboardActionExecute(file_name=<span class="string">'keyboard.action'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> action == <span class="string">'listener'</span>:</span><br><span class="line">        <span class="keyword">if</span> startListenerBtn[<span class="string">'text'</span>] == <span class="string">'录制'</span>:</span><br><span class="line">            m1.start()</span><br><span class="line">            startListenerBtn[<span class="string">'text'</span>] = <span class="string">'录制中...esc停止录制'</span></span><br><span class="line">            startListenerBtn[<span class="string">'state'</span>] = <span class="string">'disabled'</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">elif</span> tene<span class="string">r'))</span></span><br><span class="line"><span class="string">    startListenerBtn.place(x=10, y=10, width=180, height=80)</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    startExecuteBtn = tkinter.Button(root, text="回放", command=lambda: button_onClick('</span>execute<span class="string">'))</span></span><br><span class="line"><span class="string">    startExecuteBtn.place(x=10, y=110, width=180, height=80)</span></span><br><span class="line"><span class="string">    root.mainloop()</span></span><br></pre></td></tr></table></figure>
<p>键盘精灵的录制和回放程序到这里以及算是一个基础版本了，可以正常使用。并且新增了esc键监听，当用户点击esc时将会结束录制。<br><code>鼠标精灵</code>和<code>键盘精灵</code>都可以单独的运行使用。<br>大多数场景下这两者的功能都会使用到，所以接下来我要实现一个完成的<code>按键精灵</code>，同时包含鼠标和键盘的录制回放功能。<br>在之前的代码基础上进一步封装。</p>
<p>考虑的基本要素如下：</p>
<ol>
<li>记录鼠标和记录键盘的事件采用不同的json模板进行定义，采用响应式对用户的操作进行监听，用户静止不动则不会写入文件。</li>
<li>同时监听鼠标和键盘，为了避免多线程写同一个文件的锁操作，我将鼠标和键盘的录制记录分为两个不同的文件。</li>
<li>录制和回放的操作通常都需要有一个等待时间的设置，所以代码里加上了GUI的设置部分，GUI没有设计所以后续这块代码要优化。</li>
<li>考虑录制和回放倒计时需要UI提示用户并且定时触发线程执行，所以封装了一个UI更新线程的类。</li>
</ol>
<p>按键精灵0.1版本完整代码如下：</p>
<h1 id="键鼠录制的按键精灵0-1版本"><a href="#键鼠录制的按键精灵0-1版本" class="headerlink" title="键鼠录制的按键精灵0.1版本"></a>键鼠录制的按键精灵0.1版本</h1><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> json</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> tkinter</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> pynput <span class="keyword">import</span> keyboard, mouse</span><br><span class="line"><span class="keyword">from</span> pynput.keyboard <span class="keyword">import</span> Controller <span class="keyword">as</span> KeyBoardController, KeyCode</span><br><span class="line"><span class="keyword">from</span> pynput.mouse <span class="keyword">import</span> Button, Controller <span class="keyword">as</span> MouseController</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 键盘动作模板</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">keyboard_action_template</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        <span class="string">"name"</span>: <span class="string">"keyboard"</span>,</span><br><span class="line">        <span class="string">"event"</span>: <span class="string">"default"</span>,</span><br><span class="line">        <span class="string">"vk"</span>: <span class="string">"default"</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标动作模板</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">mouse_action_template</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        <span class="string">"name"</span>: <span class="string">"mouse"</span>,</span><br><span class="line">        <span class="string">"event"</span>: <span class="string">"default"</span>,</span><br><span class="line">        <span class="string">"target"</span>: <span class="string">"default"</span>,</span><br><span class="line">        <span class="string">"action"</span>: <span class="string">"default"</span>,</span><br><span class="line">        <span class="string">"location"</span>: &#123;</span><br><span class="line">            <span class="string">"x"</span>: <span class="string">"0"</span>,</span><br><span class="line">            <span class="string">"y"</span>: <span class="string">"0"</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 倒计时监听，更新UI触发自定义线程对象</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UIUpdateCutDownExecute</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, cut_down_time, custom_thread_list)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.cut_down_time = cut_down_time</span><br><span class="line">        self.custom_thread_list = custom_thread_list</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">while</span> self.cut_down_time &gt; <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">for</span> custom_thread <span class="keyword">in</span> self.custom_thread_list:</span><br><span class="line">                <span class="keyword">if</span> custom_thread[<span class="string">'obj_ui'</span>] <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">                    custom_thread[<span class="string">'obj_ui'</span>][<span class="string">'text'</span>] = str(self.cut_down_time)</span><br><span class="line">                    custom_thread[<span class="string">'obj_ui'</span>][<span class="string">'state'</span>] = <span class="string">'disabled'</span></span><br><span class="line">                    self.cut_down_time = self.cut_down_time - <span class="number">1</span></span><br><span class="line">            time.sleep(<span class="number">1</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">for</span> custom_thread <span class="keyword">in</span> self.custom_thread_list:</span><br><span class="line">                <span class="keyword">if</span> custom_thread[<span class="string">'obj_ui'</span>] <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">                    custom_thread[<span class="string">'obj_ui'</span>][<span class="string">'text'</span>] = custom_thread[<span class="string">'final_text'</span>]</span><br><span class="line">                    custom_thread[<span class="string">'obj_ui'</span>][<span class="string">'state'</span>] = <span class="string">'disabled'</span></span><br><span class="line">                <span class="keyword">if</span> custom_thread[<span class="string">'obj_thread'</span>] <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">                    custom_thread[<span class="string">'obj_thread'</span>].start()</span><br><span class="line">                    time.sleep(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 键盘动作监听</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">KeyboardActionListener</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, file_name=<span class="string">'keyboard.action'</span>)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.file_name = file_name</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">with</span> open(self.file_name, <span class="string">'w'</span>, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">            <span class="comment"># 键盘按下监听</span></span><br><span class="line">            <span class="function"><span class="keyword">def</span> <span class="title">on_press</span><span class="params">(key)</span>:</span></span><br><span class="line">                template = keyboard_action_template()</span><br><span class="line">                template[<span class="string">'event'</span>] = <span class="string">'press'</span></span><br><span class="line">                <span class="keyword">try</span>:</span><br><span class="line">                    template[<span class="string">'vk'</span>] = key.vk</span><br><span class="line">                <span class="keyword">except</span> AttributeError:</span><br><span class="line">                    template[<span class="string">'vk'</span>] = key.value.vk</span><br><span class="line">                <span class="keyword">finally</span>:</span><br><span class="line">                    file.writelines(json.dumps(template) + <span class="string">"\n"</span>)</span><br><span class="line">                    file.flush()</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 键盘抬起监听</span></span><br><span class="line">            <span class="function"><span class="keyword">def</span> <span class="title">on_release</span><span class="params">(key)</span>:</span></span><br><span class="line">                <span class="keyword">if</span> key == keyboard.Key.esc:</span><br><span class="line">                    <span class="comment"># 停止监听</span></span><br><span class="line">                    startListenerBtn[<span class="string">'text'</span>] = <span class="string">'开始录制'</span></span><br><span class="line">                    startListenerBtn[<span class="string">'state'</span>] = <span class="string">'normal'</span></span><br><span class="line">                    keyboardListener.stop()</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">False</span></span><br><span class="line">                template = keyboard_action_template()</span><br><span class="line">                template[<span class="string">'event'</span>] = <span class="string">'release'</span></span><br><span class="line">                <span class="keyword">try</span>:</span><br><span class="line">                    template[<span class="string">'vk'</span>] = key.vk</span><br><span class="line">                <span class="keyword">except</span> AttributeError:</span><br><span class="line">                    template[<span class="string">'vk'</span>] = key.value.vk</span><br><span class="line">                <span class="keyword">finally</span>:</span><br><span class="line">                    file.writelines(json.dumps(template) + <span class="string">"\n"</span>)</span><br><span class="line">                    file.flush()</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 键盘监听</span></span><br><span class="line">            <span class="keyword">with</span> keyboard.Listener(on_press=on_press, on_release=on_release) <span class="keyword">as</span> keyboardListener:</span><br><span class="line">                keyboardListener.join()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 键盘动作执行</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">KeyboardActionExecute</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, file_name=<span class="string">'keyboard.action'</span>, execute_count=<span class="number">0</span>)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.file_name = file_name</span><br><span class="line">        self.execute_count = execute_count</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">while</span> self.execute_count &gt; <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">with</span> open(self.file_name, <span class="string">'r'</span>, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">                keyboard_exec = KeyBoardController()</span><br><span class="line">                line = file.readline()</span><br><span class="line">                <span class="keyword">while</span> line:</span><br><span class="line">                    obj = json.loads(line)</span><br><span class="line">                    <span class="keyword">if</span> obj[<span class="string">'name'</span>] == <span class="string">'keyboard'</span>:</span><br><span class="line">                        <span class="keyword">if</span> obj[<span class="string">'event'</span>] == <span class="string">'press'</span>:</span><br><span class="line">                            keyboard_exec.press(KeyCode.from_vk(obj[<span class="string">'vk'</span>]))</span><br><span class="line">                            time.sleep(<span class="number">0.01</span>)</span><br><span class="line"></span><br><span class="line">                        <span class="keyword">elif</span> obj[<span class="string">'event'</span>] == <span class="string">'release'</span>:</span><br><span class="line">                            keyboard_exec.release(KeyCode.from_vk(obj[<span class="string">'vk'</span>]))</span><br><span class="line">                            time.sleep(<span class="number">0.01</span>)</span><br><span class="line">                    line = file.readline()</span><br><span class="line">                startExecuteBtn[<span class="string">'text'</span>] = <span class="string">'开始回放'</span></span><br><span class="line">                startExecuteBtn[<span class="string">'state'</span>] = <span class="string">'normal'</span></span><br><span class="line">            self.execute_count = self.execute_count - <span class="number">1</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标动作监听</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MouseActionListener</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, file_name=<span class="string">'mouse.action'</span>)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.file_name = file_name</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">with</span> open(self.file_name, <span class="string">'w'</span>, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">            <span class="comment"># 鼠标移动事件</span></span><br><span class="line">            <span class="function"><span class="keyword">def</span> <span class="title">on_move</span><span class="params">(x, y)</span>:</span></span><br><span class="line">                template = mouse_action_template()</span><br><span class="line">                template[<span class="string">'event'</span>] = <span class="string">'move'</span></span><br><span class="line">                template[<span class="string">'location'</span>][<span class="string">'x'</span>] = x</span><br><span class="line">                template[<span class="string">'location'</span>][<span class="string">'y'</span>] = y</span><br><span class="line">                file.writelines(json.dumps(template) + <span class="string">"\n"</span>)</span><br><span class="line">                file.flush()</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 鼠标点击事件</span></span><br><span class="line">            <span class="function"><span class="keyword">def</span> <span class="title">on_click</span><span class="params">(x, y, button, pressed)</span>:</span></span><br><span class="line">                template = mouse_action_template()</span><br><span class="line">                template[<span class="string">'event'</span>] = <span class="string">'click'</span></span><br><span class="line">                template[<span class="string">'target'</span>] = button.name</span><br><span class="line">                template[<span class="string">'action'</span>] = pressed</span><br><span class="line">                template[<span class="string">'location'</span>][<span class="string">'x'</span>] = x</span><br><span class="line">                template[<span class="string">'location'</span>][<span class="string">'y'</span>] = y</span><br><span class="line">                file.writelines(json.dumps(template) + <span class="string">"\n"</span>)</span><br><span class="line">                file.flush()</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 鼠标滚动事件</span></span><br><span class="line">            <span class="function"><span class="keyword">def</span> <span class="title">on_scroll</span><span class="params">(x, y, x_axis, y_axis)</span>:</span></span><br><span class="line">                template = mouse_action_template()</span><br><span class="line">                template[<span class="string">'event'</span>] = <span class="string">'scroll'</span></span><br><span class="line">                template[<span class="string">'location'</span>][<span class="string">'x'</span>] = x_axis</span><br><span class="line">                template[<span class="string">'location'</span>][<span class="string">'y'</span>] = y_axis</span><br><span class="line">                file.writelines(json.dumps(template) + <span class="string">"\n"</span>)</span><br><span class="line">                file.flush()</span><br><span class="line"></span><br><span class="line">            <span class="keyword">with</span> mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) <span class="keyword">as</span> mouseListener:</span><br><span class="line">                mouseListener.join()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 鼠标动作执行</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MouseActionExecute</span><span class="params">(threading.Thread)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, file_name=<span class="string">'mouse.action'</span>, execute_count=<span class="number">0</span>)</span>:</span></span><br><span class="line">        super().__init__()</span><br><span class="line">        self.file_name = file_name</span><br><span class="line">        self.execute_count = execute_count</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">while</span> self.execute_count &gt; <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">with</span> open(self.file_name, <span class="string">'r'</span>, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">                mouse_exec = MouseController()</span><br><span class="line">                line = file.readline()</span><br><span class="line">                <span class="keyword">while</span> line:</span><br><span class="line">                    obj = json.loads(line)</span><br><span class="line">                    <span class="keyword">if</span> obj[<span class="string">'name'</span>] == <span class="string">'mouse'</span>:</span><br><span class="line">                        <span class="keyword">if</span> obj[<span class="string">'event'</span>] == <span class="string">'move'</span>:</span><br><span class="line">                            mouse_exec.position = (obj[<span class="string">'location'</span>][<span class="string">'x'</span>], obj[<span class="string">'location'</span>][<span class="string">'y'</span>])</span><br><span class="line">                            time.sleep(<span class="number">0.01</span>)</span><br><span class="line">                        <span class="keyword">elif</span> obj[<span class="string">'event'</span>] == <span class="string">'click'</span>:</span><br><span class="line">                            <span class="keyword">if</span> obj[<span class="string">'action'</span>]:</span><br><span class="line">                                <span class="keyword">if</span> obj[<span class="string">'target'</span>] == <span class="string">'left'</span>:</span><br><span class="line">                                    mouse_exec.press(Button.left)</span><br><span class="line">                                <span class="keyword">else</span>:</span><br><span class="line">                                    mouse_exec.press(Button.right)</span><br><span class="line">                            <span class="keyword">else</span>:</span><br><span class="line">                                <span class="keyword">if</span> obj[<span class="string">'target'</span>] == <span class="string">'left'</span>:</span><br><span class="line">                                    mouse_exec.release(Button.left)</span><br><span class="line">                                <span class="keyword">else</span>:</span><br><span class="line">                                    mouse_exec.release(Button.right)</span><br><span class="line">                            time.sleep(<span class="number">0.01</span>)</span><br><span class="line">                        <span class="keyword">elif</span> obj[<span class="string">'event'</span>] == <span class="string">'scroll'</span>:</span><br><span class="line">                            mouse_exec.scroll(obj[<span class="string">'location'</span>][<span class="string">'x'</span>], obj[<span class="string">'location'</span>][<span class="string">'y'</span>])</span><br><span class="line">                            time.sleep(<span class="number">0.01</span>)</span><br><span class="line">                    line = file.readline()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">command_adapter</span><span class="params">(action)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> action == <span class="string">'listener'</span>:</span><br><span class="line">        <span class="keyword">if</span> startListenerBtn[<span class="string">'text'</span>] == <span class="string">'开始录制'</span>:</span><br><span class="line">            custom_thread_list = [</span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="string">'obj_thread'</span>: KeyboardActionListener(),</span><br><span class="line">                    <span class="string">'obj_ui'</span>: startListenerBtn,</span><br><span class="line">                    <span class="string">'final_text'</span>: <span class="string">'录制中...esc停止录制'</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="string">'obj_thread'</span>: MouseActionListener(),</span><br><span class="line">                    <span class="string">'obj_ui'</span>: <span class="keyword">None</span>,</span><br><span class="line">                    <span class="string">'final_text'</span>: <span class="keyword">None</span></span><br><span class="line">                &#125;</span><br><span class="line">            ]</span><br><span class="line">            UIUpdateCutDownExecute(startTime.get(), custom_thread_list).start()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">elif</span> action == <span class="string">'execute'</span>:</span><br><span class="line">        <span class="keyword">if</span> startExecuteBtn[<span class="string">'text'</span>] == <span class="string">'开始回放'</span>:</span><br><span class="line">            custom_thread_list = [</span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="string">'obj_thread'</span>: KeyboardActionExecute(execute_count=playCount.get()),</span><br><span class="line">                    <span class="string">'obj_ui'</span>: startExecuteBtn,</span><br><span class="line">                    <span class="string">'final_text'</span>: <span class="string">'回放中...关闭程序停止回放'</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                    <span class="string">'obj_thread'</span>: MouseActionExecute(execute_count=playCount.get()),</span><br><span class="line">                    <span class="string">'obj_ui'</span>: <span class="keyword">None</span>,</span><br><span class="line">                    <span class="string">'final_text'</span>: <span class="keyword">None</span></span><br><span class="line">                &#125;</span><br><span class="line">            ]</span><br><span class="line">            UIUpdateCutDownExecute(endTime.get(), custom_thread_list).start()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">isNumber</span><span class="params">(content)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> content.isdigit() <span class="keyword">or</span> content == <span class="string">""</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">True</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">False</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    root = tkinter.Tk()</span><br><span class="line">    root.title(<span class="string">'按键精灵-蓝士钦'</span>)</span><br><span class="line">    root.geometry(<span class="string">'200x200+400+100'</span>)</span><br><span class="line"></span><br><span class="line">    listenerStartLabel = tkinter.Label(root, text=<span class="string">'录制倒计时'</span>)</span><br><span class="line">    listenerStartLabel.place(x=<span class="number">10</span>, y=<span class="number">10</span>, width=<span class="number">80</span>, height=<span class="number">20</span>)</span><br><span class="line">    startTime = tkinter.IntVar()</span><br><span class="line">    listenerStartEdit = tkinter.Entry(root, textvariable=startTime)</span><br><span class="line">    listenerStartEdit.place(x=<span class="number">100</span>, y=<span class="number">10</span>, width=<span class="number">60</span>, height=<span class="number">20</span>)</span><br><span class="line">    startTime.set(<span class="number">3</span>)</span><br><span class="line"></span><br><span class="line">    listenerTipLabel = tkinter.Label(root, text=<span class="string">'秒'</span>)</span><br><span class="line">    listenerTipLabel.place(x=<span class="number">160</span>, y=<span class="number">10</span>, width=<span class="number">20</span>, height=<span class="number">20</span>)</span><br><span class="line"></span><br><span class="line">    startListenerBtn = tkinter.Button(root, text=<span class="string">"开始录制"</span>, command=<span class="keyword">lambda</span>: command_adapter(<span class="string">'listener'</span>))</span><br><span class="line">    startListenerBtn.place(x=<span class="number">10</span>, y=<span class="number">45</span>, width=<span class="number">180</span>, height=<span class="number">30</span>)</span><br><span class="line"></span><br><span class="line">    executeEndLabel = tkinter.Label(root, text=<span class="string">'回放倒计时'</span>)</span><br><span class="line">    executeEndLabel.place(x=<span class="number">10</span>, y=<span class="number">85</span>, width=<span class="number">80</span>, height=<span class="number">20</span>)</span><br><span class="line">    endTime = tkinter.IntVar()</span><br><span class="line">    executeEndEdit = tkinter.Entry(root, textvariable=endTime)</span><br><span class="line">    executeEndEdit.place(x=<span class="number">100</span>, y=<span class="number">85</span>, width=<span class="number">60</span>, height=<span class="number">20</span>)</span><br><span class="line">    endTime.set(<span class="number">6</span>)</span><br><span class="line"></span><br><span class="line">    executeTipLabel = tkinter.Label(root, text=<span class="string">'秒'</span>)</span><br><span class="line">    executeTipLabel.place(x=<span class="number">160</span>, y=<span class="number">85</span>, width=<span class="number">20</span>, height=<span class="number">20</span>)</span><br><span class="line"></span><br><span class="line">    playCountLabel = tkinter.Label(root, text=<span class="string">'回放次数'</span>)</span><br><span class="line">    playCountLabel.place(x=<span class="number">10</span>, y=<span class="number">115</span>, width=<span class="number">80</span>, height=<span class="number">20</span>)</span><br><span class="line">    playCount = tkinter.IntVar()</span><br><span class="line">    playCountEdit = tkinter.Entry(root, textvariable=playCount)</span><br><span class="line">    playCountEdit.place(x=<span class="number">100</span>, y=<span class="number">115</span>, width=<span class="number">60</span>, height=<span class="number">20</span>)</span><br><span class="line">    playCount.set(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line">    playCountTipLabel = tkinter.Label(root, text=<span class="string">'次'</span>)</span><br><span class="line">    playCountTipLabel.place(x=<span class="number">160</span>, y=<span class="number">115</span>, width=<span class="number">20</span>, height=<span class="number">20</span>)</span><br><span class="line"></span><br><span class="line">    startExecuteBtn = tkinter.Button(root, text=<span class="string">"开始回放"</span>, command=<span class="keyword">lambda</span>: command_adapter(<span class="string">'execute'</span>))</span><br><span class="line">    startExecuteBtn.place(x=<span class="number">10</span>, y=<span class="number">145</span>, width=<span class="number">180</span>, height=<span class="number">30</span>)</span><br><span class="line">    root.mainloop()</span><br></pre></td></tr></table></figure>
<p>脚本精灵0.1版本完成😋</p>
<img src="/2fb233e2/mouse_keyboard_py.png" title="mouse_keyboard_py">
<p>还需要考虑的点：</p>
<ol>
<li>键盘事件没有记录用户每个动作之间的延迟时间，无法准确重放用户的输入节奏，后续考虑记录时间间隔点。</li>
<li>鼠标事件用户移动的越快，产生的点位变化也就越频繁，所以鼠标在回放时的速度与用户的操作基本一致。</li>
<li>鼠标没有停止回放的快捷键，要考虑如何停止回放鼠标事件。</li>
<li>输入法切换可能导致重放键盘按键时输入不准确，需要录制时是什么输入状态，重放时也要对应的键盘属性和状态</li>
<li>…还有很多需要考虑的点(原本只是想简单的做个示例程序)</li>
</ol>
<p>程序只在MacOS平台上实验过，其他平台还未实验，一个相对完整的按键精灵在录制时应该获取更多的信息，这样在回放的时候才足够准确，后续考虑做一个更加精确的按键精灵，比如加入获取屏幕像素点，回放时通过采样比对，达到为所欲为功能。<br>GitHub地址：<br><a href="https://github.com/lanshiqin/JerryMouse" target="_blank" rel="noopener">https://github.com/lanshiqin/JerryMouse</a><br>期待大家来一起完善它😋</p>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/204682e6/index.html" rel="next" title="使用Python提高工作效率之SQLite">
                <i class="fa fa-chevron-left"></i> 使用Python提高工作效率之SQLite
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/cb6b0010/index.html" rel="prev" title="消息队列知识点梳理">
                消息队列知识点梳理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div id="gitalk-container"></div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.png"
                alt="蓝士钦" />
            
              <p class="site-author-name" itemprop="name">蓝士钦</p>
              <p class="site-description motion-element" itemprop="description">编程是一种信仰</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">36</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">7</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">12</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/lanshiqin" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/l18120788756" target="_blank" title="Weibo"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.jianshu.com/u/082f73dac819" target="_blank" title="JianShu"><i class="fa fa-fw fa-heartbeat"></i>JianShu</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:lanshiqin@outlook.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#鼠标事件监听"><span class="nav-number">1.</span> <span class="nav-text">鼠标事件监听</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#鼠标事件执行"><span class="nav-number">2.</span> <span class="nav-text">鼠标事件执行</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#带录制回放功能的鼠标精灵"><span class="nav-number">3.</span> <span class="nav-text">带录制回放功能的鼠标精灵</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#键盘事件监听"><span class="nav-number">4.</span> <span class="nav-text">键盘事件监听</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#键盘事件执行"><span class="nav-number">5.</span> <span class="nav-text">键盘事件执行</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#带录制回放功能的键盘精灵"><span class="nav-number">6.</span> <span class="nav-text">带录制回放功能的键盘精灵</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#键鼠录制的按键精灵0-1版本"><span class="nav-number">7.</span> <span class="nav-text">键鼠录制的按键精灵0.1版本</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">蓝士钦</span>

  

  
</div>










  <div class="footer-custom">闽ICP备15027850号</div>


        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
	
    

    
  </div>

  

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.4.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.1"></script>
<script src="/js/src/photoswipe.js?v="></script>
<script src="/js/src/photoswipe-ui-default.js?v="></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.1"></script>



  



  










  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
   <script type="text/javascript">
        var gitalk = new Gitalk({
          clientID: '08543e172f1359fce9c3',
          clientSecret: 'a8dd355f95e5035e0266c695e489fa991c9d28e2',
          repo: 'lanshiqin-blog',
          owner: 'lanshiqin',
          admin: ['lanshiqin'],
          id: location.pathname,
          distractionFreeMode: 'true'
        })
        gitalk.render('gitalk-container')           
       </script>

  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
<!-- 页面点击小红心 --> 
<script type="text/javascript" src="/js/src/love.js"></script>
<!--崩溃欺骗-->
<script type="text/javascript" src="/js/src/crash_cheat.js"></script>